package com.teamwe.movecard.service;

import com.teamwe.movecard.domain.Score;
import com.teamwe.movecard.repository.ScoreRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Slf4j
@Service
public class ScoreService {

    @Autowired
    ScoreRepository scoreRepo;

    /**
     * 获取排行榜的信息(前五)
     * @return
     */
    public List<Score> getRankList(){
        return  (List<Score>) scoreRepo.getRankList();
    }

    /**
     * 获取个人的排行位置,当用户不存在时返回-1
     * @param opneId
     * @return
     */
    public int getRankByOpenId(String opneId){
        List<Score> list = scoreRepo.getAllListDesc();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getMpOpenId().equals(opneId))
                return i + 1;
        }
        return -1;
    }

    public Score getUserScore(String mpOpenId){
        return  scoreRepo.getByUserMpOpenId(mpOpenId);
    }

    /**
     * 保存用户分数,会将分数累加到用户该用户上
     * @param score
     */
    public void saveScore(Score score) throws Exception{
        Score newScore = null;
        try {
            newScore = scoreRepo.findById(score.getMpOpenId()).get();
            int allScore = newScore.getScore() + score.getScore();
            newScore.setScore(allScore);
        } catch (Exception e) {
            log.info("用户[{}]不存在，插入新的用户记录", score.getMpOpenId());
            newScore = score;
        } finally {
            if(newScore != null){
                scoreRepo.save(newScore);
            }else {
                throw new Exception();
            }
        }
    }
}
